# -*- coding: utf-8 -*-
"""Generate V2 subtitle files with correct timing matching voiceover segments."""

import json
import os

# V2 segment boundaries from actual voiceover durations
seg_boundaries = [
    (0.0, 8.93),    # seg_01_title
    (8.93, 18.17),  # seg_02_recording_fail
    (18.17, 26.43), # seg_03_ai_drift
    (26.43, 36.61), # seg_04_ui_render
    (36.61, 49.09), # seg_05_kimi_score
    (49.09, 58.81), # seg_06_v10_crash
    (58.81, 69.03), # seg_07_rollback
    (69.03, 80.5),  # seg_08_deploy
    (80.5, 91.37),  # seg_09_ending
]

# Each segment has list of chunks, each chunk is a list of display lines (max 2, max 13 chars each)
seg_chunks_nested = [
    # Seg 1 (0-8.93s)
    [
        ["我让 Claude Code", "自己做视频"],
        ["录屏失败", "AI 跑偏"],
        ["从 69 爬到 92", "这是真实工作流"],
    ],
    # Seg 2 (8.93-18.17s)
    [
        ["想录下执行过程", "但 Windows 抓不到后台桌面"],
        ["五种方案全是空文件", "录屏彻底失败"],
    ],
    # Seg 3 (18.17-26.43s)
    [
        ["更糟的是", "Claude Code 跑偏了"],
        ["跑去研究亚马逊", "ChatGPT 说：别录了"],
        ["让它自己画界面"],
    ],
    # Seg 4 (26.43-36.61s)
    [
        ["于是换条路", "Python 画终端和工具卡片"],
        ["四个 AI 并行跑", "进度条在涨"],
        ["每条命令来自真实日志"],
    ],
    # Seg 5 (36.61-49.09s)
    [
        ["每轮渲染完", "Kimi 审核打分"],
        ["v1 只有 69", "改字体到 72"],
        ["加动画跳到 81", "v4 85，v6 89"],
        ["v9 冲到 92"],
    ],
    # Seg 6 (49.09-58.81s)
    [
        ["V9 冲到 92", "马上要发布"],
        ["但下轮硬编码没改", "画面四个代理底部显示三个"],
        ["92 砸到 76"],
    ],
    # Seg 7 (58.81-69.03s)
    [
        ["下轮修了六个问题", "回到 88"],
        ["但回不到 92 了", "最终回滚 V9 冻结"],
        ["一个硬编码 bug", "一夜回到解放前"],
    ],
    # Seg 8 (69.03-80.5s)
    [
        ["V9 上线审核门户", "HTTP 200 通过"],
        ["11 轮迭代 1 次崩溃", "69 到 92"],
        ["AI 自己审核", "修复、部署"],
    ],
    # Seg 9 (80.5-91.37s)
    [
        ["录屏失败", "AI 跑偏"],
        ["分数崩过", "又爬回来"],
        ["这才是真正的 AI 工作流"],
        ["执行、审核、修复", "回归、交付"],
    ],
]

# Keywords to highlight in yellow
HIGHLIGHT_KEYWORDS = [
    "录屏失败", "AI 跑偏", "真实日志", "Kimi 审核",
    "69", "92", "76", "88", "81", "85", "89", "72",
    "回滚", "冻结", "HTTP 200", "审核门户",
    "Claude Code", "ChatGPT", "bug",
]

output_dir = "E:/集群文件夹/factory_os/short_video_real_data_pipeline/phase4b_90s_formal_sample/v22_kimi_claude_loop/full_story_douyin_video/04_subtitles/v2"

# Build flat list of chunks with times
chunks_with_time = []
for seg_idx, (seg_start, seg_end) in enumerate(seg_boundaries):
    chunks_list = seg_chunks_nested[seg_idx]
    seg_dur = seg_end - seg_start
    num_chunks = len(chunks_list)
    chunk_dur = seg_dur / num_chunks
    for ci, chunk_lines in enumerate(chunks_list):
        chunk_start = seg_start + ci * chunk_dur
        chunk_end = chunk_start + chunk_dur
        chunks_with_time.append((chunk_start, chunk_end, chunk_lines))

print(f"Total subtitle chunks: {len(chunks_with_time)}")
for i, (s, e, lines) in enumerate(chunks_with_time):
    display = " | ".join(lines)
    print(f"  {i+1}. {s:.1f}s-{e:.1f}s: {display}")

# --- Helper functions ---
def to_srt_time(seconds):
    h = int(seconds // 3600)
    m = int((seconds % 3600) // 60)
    s = int(seconds % 60)
    ms = int((seconds - int(seconds)) * 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"

def to_ass_time(seconds):
    h = int(seconds // 3600)
    m = int((seconds % 3600) // 60)
    s = seconds % 60
    return f"{h}:{m:02d}:{s:05.2f}"

# --- Generate SRT ---
srt_lines = []
for i, (start, end, lines) in enumerate(chunks_with_time, 1):
    srt_lines.append(str(i))
    srt_lines.append(f"{to_srt_time(start)} --> {to_srt_time(end)}")
    srt_lines.append("\n".join(lines))
    srt_lines.append("")

with open(f"{output_dir}/captions_final_v2.srt", "w", encoding="utf-8") as f:
    f.write("\n".join(srt_lines))
print(f"SRT saved: {len(chunks_with_time)} chunks")

# --- Generate ASS ---
ass_header = """[Script Info]
; V2 subtitles for full story douyin video
ScriptType: v4.00+
PlayResX: 1080
PlayResY: 1920
WrapStyle: 1
ScaledBorderAndShadow: yes

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Microsoft YaHei,52,&H00FFFFFF,&H0000FF00,&H00000000,&H64000000,0,0,0,0,100,100,0,0,1,3,1,2,60,60,120,1
Style: Highlight,Microsoft YaHei,52,&H0000FFFF,&H0000FF00,&H00000000,&H64000000,0,0,0,0,100,100,0,0,1,3,1,2,60,60,120,1

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
"""

def has_highlight_word(lines):
    """Check if any line contains a highlight keyword."""
    combined = " ".join(lines)
    for kw in HIGHLIGHT_KEYWORDS:
        if kw in combined:
            return True
    return False

def build_ass_text(lines):
    """Build ASS text with keyword highlighting."""
    combined = "\\N".join(lines)
    result = combined
    for kw in sorted(HIGHLIGHT_KEYWORDS, key=len, reverse=True):
        if kw in result:
            replacement = r"{\c&H00FFFF&\b1}" + kw + r"{\c&HFFFFFF&\b0}"
            result = result.replace(kw, replacement)
    return result

ass_events = []
for start, end, lines in chunks_with_time:
    ass_text = build_ass_text(lines)
    style = "Highlight" if has_highlight_word(lines) else "Default"
    ass_events.append(
        f"Dialogue: 0,{to_ass_time(start)},{to_ass_time(end)},{style},,0,0,0,,{ass_text}"
    )

ass_content = ass_header + "\n".join(ass_events)
with open(f"{output_dir}/captions_final_v2.ass", "w", encoding="utf-8") as f:
    f.write(ass_content)
print(f"ASS saved: {len(ass_events)} events")

# --- Generate captions_words_v2.json ---
captions_words = {
    "whisper_model": "base+manual_align",
    "base_voiceover": "voiceover_master_v2.wav",
    "total_duration_sec": 91.37,
    "segments": []
}

for start, end, lines in chunks_with_time:
    combined_text = "".join(lines)
    chars = list(combined_text)
    char_duration = (end - start) / max(len(chars), 1) if chars else 0
    words = []
    for j, ch in enumerate(chars):
        words.append({
            "word": ch,
            "start": round(start + j * char_duration, 2),
            "end": round(start + (j + 1) * char_duration, 2)
        })

    captions_words["segments"].append({
        "start": start,
        "end": end,
        "text": "\n".join(lines),
        "words": words
    })

with open(f"{output_dir}/captions_words_v2.json", "w", encoding="utf-8") as f:
    json.dump(captions_words, f, ensure_ascii=False, indent=2)
print(f"captions_words_v2.json updated: {len(chunks_with_time)} segments")

print("\nAll subtitle files generated successfully!")
